import 'package:flutter/material.dart';
import 'dart:convert';
import './client_dio.dart';

class LoginScreen extends StatefulWidget {
  const LoginScreen({Key? key}) : super(key: key);

  @override
  State<LoginScreen> createState() => _LoginScreenState();
}

class _LoginScreenState extends State<LoginScreen> {
  late TextEditingController _usernameController;
  late TextEditingController _passwordController;

  @override
  void initState() {
    super.initState();
    _usernameController = TextEditingController(text: '马红权');
    _passwordController = TextEditingController(text: '333333');
  }

  @override
  void dispose() {
    _usernameController.dispose();
    _passwordController.dispose();
    super.dispose();
  }

  void _handleLogin() {
    String username = _usernameController.text;
    String password = _passwordController.text;
    
    if (username.isEmpty || password.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('请输入用户名和密码')),
      );
      return;
    }
    
    login(username, password, (r) {
      // 处理登录成功的情况
      Map<String, dynamic> responseData;
      if (r is String) {
        try {
          responseData = jsonDecode(r) as Map<String, dynamic>;
        } catch (e) {
          print('解析登录响应失败: $e');
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text('登录失败：解析响应错误')),
          );
          return;
        }
      } else if (r is Map<String, dynamic>) {
        responseData = r;
      } else {
        print('登录响应类型错误: ${r.runtimeType}');
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('登录失败：响应类型错误')),
        );
        return;
      }
      
      // 返回登录结果
      Navigator.pop(context, {
        'user': responseData['data']['name'] ?? responseData['user'] ?? username,
        'token': responseData['token'] ?? '',
      });
    }, (e) {
      // 处理登录失败的情况
      print('登录失败: $e');
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('登录失败：$e')),
      );
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('登录界面'),
      ),
      body: Center(
        child: Padding(
          padding: EdgeInsets.all(16.0),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              TextField(
                controller: _usernameController,
                decoration: InputDecoration(
                  labelText: '用户名',
                  border: OutlineInputBorder(),
                ),
              ),
              SizedBox(height: 16.0),
              TextField(
                controller: _passwordController,
                decoration: InputDecoration(
                  labelText: '密码',
                  border: OutlineInputBorder(),
                ),
                obscureText: true,
              ),
              SizedBox(height: 24.0),
              ElevatedButton(
                onPressed: _handleLogin,
                child: Text('登录'),
                style: ElevatedButton.styleFrom(
                  minimumSize: Size(double.infinity, 50),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}